const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const cors = require("cors");
const swaggerJsdoc = require("swagger-jsdoc");  // 引入 swagger-jsdoc
const swaggerUi = require("swagger-ui-express");  // 引入 swagger-ui-express

// 引入各路由模块
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const adminAuthRouter = require("./routes/admin/auth");
const enterpriseRoutes = require("./routes/admin/enterpriseRoutes");
const enterpriseRelationsRoutes = require("./routes/admin/relationsRoutes");

const app = express();

// Swagger 配置
const swaggerDefinition = {
  openapi: "3.0.0",
  info: {
    title: "企业管理系统 API",
    version: "1.0.0",
    description: "这是一个企业管理系统的 API 文档",
  },
  servers: [
    {
      url: "http://localhost:3000",  // 根据你的开发环境调整
    },
  ],
};

// Swagger 配置选项
const options = {
  swaggerDefinition,
  apis: ["./routes/admin/*.js", "./routes/*.js"],  // 指定 API 路由文件所在位置
};

const swaggerSpec = swaggerJsdoc(options);

// 使用 swagger-ui-express 中间件
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec));

// 配置其他中间件
app.use(cors());
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

// 路由配置
app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/admin/auth", adminAuthRouter);
app.use("/admin/enterprises", enterpriseRoutes);
app.use("/admin/relations", enterpriseRelationsRoutes);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`🚀 Server running at http://localhost:${PORT}`);
});

module.exports = app;
